package com.xianniu.ltc.service.impl;

import cn.devezhao.persist4j.engine.ID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rebuild.core.Application;
import com.rebuild.core.UserContextHolder;
import com.rebuild.core.metadata.EntityHelper;
import com.xianniu.ltc.common.Constant;
import com.xianniu.ltc.mapper.TGonghaixiansuoMapper;
import com.xianniu.ltc.mapper.TSihaixiansuoMapper;
import com.xianniu.ltc.mapper.TXnLeadMapper;
import com.xianniu.ltc.mapper.TXnLeadTeamMapper;
import com.xianniu.ltc.model.entity.*;
import com.xianniu.ltc.model.po.AddXnLeadTeamPO;
import com.xianniu.ltc.model.po.QueryLeadTeamAdminPO;
import com.xianniu.ltc.model.po.TransferTeamPO;
import com.xianniu.ltc.model.po.UpdateLeadTeamPO;
import com.xianniu.ltc.model.vo.XnLeadTeamVO;
import com.xianniu.ltc.service.XnLeadTeamService;
import com.xxl.sso.core.entity.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author WangRuiJie
 * @Title: XnLeadTeamServiceImpl
 * @Package com.xianniu.ltc.service.impl
 * @Description:
 * @date 2021/6/911:24 上午
 */
@Slf4j
@Service
public class XnLeadTeamServiceImpl implements XnLeadTeamService {

    @Resource
    private TXnLeadTeamMapper tXnLeadTeamMapper;

    @Resource
    private TXnLeadMapper leadMapper;

    @Resource
    private TSihaixiansuoMapper sihaixiansuoMapper;
    @Resource
    private TGonghaixiansuoMapper gonghaixiansuoMapper;


    @Override
    public IPage<XnLeadTeamVO> selectLeadForAdmin(QueryLeadTeamAdminPO po) {
        Page<TXnLeadTeamDTO> page = new Page<>(po.getPageNum(), po.getPageSize());
        IPage<XnLeadTeamVO> dtoList = tXnLeadTeamMapper.selectPageList(page, po, UserContextHolder.getTenant());
        if (CollectionUtils.isNotEmpty(dtoList.getRecords())){
            for (XnLeadTeamVO v :dtoList.getRecords()) {
                 // 逗号分割为数组
                String[] headBy = v.getHeadBy().split(",");
                String[] headByName = new String[headBy.length];
                for (int i=0;i<headBy.length;i++) {
                    String fullName;
                    try{
                        fullName = Application.getUserStore().getUser(ID.valueOf(headBy[i])).getFullName();
                    }catch (Exception e){
                        fullName = "";
                    }
                    headByName[i] = fullName;
                }
                // 重新赋值
                v.setHeadBy(StringUtils.join(headByName,","));
            }
        }
        return dtoList;
    }

    @Override
    public ReturnT addLeadTeamForAdmin(AddXnLeadTeamPO po) {
        // 查询线索组名称是否已存在
        QueryWrapper<TXnLeadTeamDTO> wrapper = new QueryWrapper<>();
        wrapper.eq("team_name", po.getTeamName());
        TXnLeadTeamDTO dto = tXnLeadTeamMapper.selectOne(wrapper);
        if (Objects.nonNull(dto)){
            return new ReturnT(400, "线索组名称已存在");
        }
        // 查询线索组名称是否已存在
        ID userId= ID.newId(EntityHelper.XnLeadTeam);
        TXnLeadTeamDTO teamDTO = new TXnLeadTeamDTO();
        BeanUtils.copyProperties(po, teamDTO);
        teamDTO.setTeamId(String.valueOf(userId));
        teamDTO.setModifiedBy(po.getCreatedBy());
        int result =  tXnLeadTeamMapper.insert(teamDTO);
        return result>0? new ReturnT(200,"操作成功"):new ReturnT(400, "操作失败");
    }

    @Override
    public ReturnT transferLeadTeamForAdmin(TransferTeamPO po) {
        // 查询线索组名称是否已存在
        QueryWrapper<TXnLeadTeamDTO> wrapperFrom = new QueryWrapper<>();
        wrapperFrom.eq("team_id", po.getFromLeadTeamId());
        TXnLeadTeamDTO dtoFrom = tXnLeadTeamMapper.selectOne(wrapperFrom);
        if (Objects.isNull(dtoFrom)){
            return new ReturnT(400, "源线索组不存在");
        }

        // 查询线索组名称是否已存在
        QueryWrapper<TXnLeadTeamDTO> wrapperTo = new QueryWrapper<>();
        wrapperTo.eq("team_id", po.getToLeadTeamId());
        TXnLeadTeamDTO dtoTo = tXnLeadTeamMapper.selectOne(wrapperTo);
        if (Objects.isNull(dtoTo)){
            return new ReturnT(400, "目标线索组不存在");
        }
        // 根据源线索组名称修改私海线索的线索组名称为目标线索组
        leadMapper.transferPLeadTeamForAdmin(dtoFrom.getTeamName(), dtoTo.getTeamName());
        // 根据源线索组名称修改公海线索的线索组名称为目标线索组
        leadMapper.transferCLeadTeamForAdmin(dtoFrom.getTeamName(), dtoTo.getTeamName());
        return new ReturnT(200,"操作成功");
    }

    @Override
    public ReturnT updateLeadTeamForAdmin(UpdateLeadTeamPO po) {
        TXnLeadTeamDTO dto = new TXnLeadTeamDTO();
        BeanUtils.copyProperties(po, dto);
        dto.setModifiedOn(new Date());
        UpdateWrapper<TXnLeadTeamDTO> wrapper = new UpdateWrapper<>();
        wrapper.eq("team_id", po.getMetadata().getId());
        int i = tXnLeadTeamMapper.update(dto, wrapper);
        return i>0? new ReturnT(200,"操作成功"):new ReturnT(400, "操作失败");
    }

    @Override
    public ReturnT deleteLeadTeamForAdmin(String teamId) {
        // 查询客户组名称是否已存在
        QueryWrapper<TXnLeadTeamDTO> wrapperFrom = new QueryWrapper<>();
        wrapperFrom.eq("team_id", teamId);
        TXnLeadTeamDTO dtoFrom = tXnLeadTeamMapper.selectOne(wrapperFrom);
        if (Objects.isNull(dtoFrom)){
            return new ReturnT(400, "线索组不存在");
        }

        QueryWrapper<TSihaixiansuoDTO> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("lead_team", dtoFrom.getTeamName());
        // 查询当前客户组是否还有私海客户
        List<TSihaixiansuoDTO> dtoList1 = sihaixiansuoMapper.selectList(wrapper1);
        if (!dtoList1.isEmpty()) {
            return new ReturnT(400,"线索组存在数据，不允许删除");
        }
        // 查询当前客户组是否还有公海客户
        QueryWrapper<TGonghaixiansuoDTO> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("lead_team", dtoFrom.getTeamName());
        List<TGonghaixiansuoDTO> dtoList2 = gonghaixiansuoMapper.selectList(wrapper2);
        if (!dtoList2.isEmpty()) {
            return new ReturnT(400,"线索组存在数据，不允许删除");
        }
        if(teamId.equals(Constant.DEFAULT_TEAM_NAME) || teamId.equals(Constant.DEFAULT_TEAM_NAME2)){
            return new ReturnT(400,"默认线索组不能删除");
        }
        // 根据ID删除线索组
        int i = tXnLeadTeamMapper.deleteById(teamId);
        return i>0? new ReturnT(200,"操作成功"):new ReturnT(400, "操作失败");
    }
}
